//
//  OSSManager.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/4.
//

import Foundation
import AliyunOSSiOS
import Combine

class OSSAuthManager {
    static let shared = OSSAuthManager()
    private var client: OSSClient?
    
    func setupSTSClient(endpoint: String, tokenProvider: @escaping () -> OSSFederationToken?) {
        let credentialProvider = OSSFederationCredentialProvider {
            return tokenProvider() // 从服务器获取临时凭证
        }
        client = OSSClient(endpoint: endpoint, credentialProvider: credentialProvider)
    }
}

extension OSSAuthManager {
    /// 增强版图片上传方法
    /// - Parameters:
    ///   - image: 要上传的UIImage对象
    ///   - bucket: OSS存储空间名称
    ///   - objectKey: 对象存储路径
    ///   - compressionQuality: 压缩质量(0-1)，默认0.7
    ///   - maxFileSize: 最大文件大小(KB)，默认500KB
    ///   - completion: 完成回调
    func uploadImage(
        _ image: UIImage,
        to bucket: String,
        objectKey: String,
        compressionQuality: CGFloat = 0.7,
        maxFileSize: Int = 500,
        completion: @escaping (Bool, Error?) -> Void
    ) {
        guard let client = client else {
            completion(false, NSError(domain: "OSSAuthManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "OSS client not initialized"]))
            return
        }
        
        // 多阶段压缩处理
        guard let imageData = autoreleasepool(invoking: {
            return compressImage(image, quality: compressionQuality, maxFileSize: maxFileSize)
        }) else {
            completion(false, NSError(domain: "OSSAuthManager", code: -2, userInfo: [NSLocalizedDescriptionKey: "Image compression failed"]))
            return
        }
        
        let putRequest = OSSPutObjectRequest()
        putRequest.bucketName = bucket
        putRequest.objectKey = objectKey
        putRequest.uploadingData = imageData
        
        // 添加上传进度回调
        putRequest.uploadProgress = { bytesSent, totalBytesSent, totalBytesExpectedToSend in
            let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
            print("Upload progress: \(progress * 100)%")
        }
        client.putObject(putRequest).continue({ task -> Any? in
            DispatchQueue.main.async {
                if let error = task.error {
                    print("Upload failed: \(error.localizedDescription)")
                    completion(false, error)
                } else {
                    print("Upload successful. Object URL: https://\(bucket).oss-cn-shenzhen.aliyuncs.com/\(objectKey)")
                    completion(true, nil)
                }
            }
            return nil
        })
    }
    
    /// 智能图片压缩方法
    private func compressImage(_ image: UIImage, quality: CGFloat, maxFileSize: Int) -> Data? {
        var compression: CGFloat = quality
        var imageData = image.jpegData(compressionQuality: compression)
        let maxBytes = maxFileSize * 1024
        // 循环压缩直到满足大小要求或达到最低质量
        while let data = imageData, data.count > maxBytes && compression > 0.1 {
            compression -= 0.1
            imageData = image.jpegData(compressionQuality: compression)
        }
        return imageData
    }
}

